package cn.flant.cmd;

import cn.flant.io.tcp.SocketHandler;

public class FilterChain {
	private class ChainItem {
		Filter filter;
		ChainItem next;
	}

	private ChainItem head;
	private ChainItem tail;

	public synchronized void addFilter(Filter filter) {
		if (tail == null) {
			tail = new ChainItem();
			tail.filter = filter;
			head = tail;
		} else {
			ChainItem next = new ChainItem();
			next.filter = filter;
			tail.next = next;
			tail = next;
		}
	}

	protected void onConncted(SocketHandler handler) throws Exception {
		ChainItem next = head;
		while (next != null) {
			next.filter.onConnected(handler);
			next = next.next;
		}
	}

	protected void onClosed(SocketHandler handler) throws Exception {
		ChainItem next = head;
		while (next != null) {
			next.filter.onClosed(handler);
			next = next.next;
		}
	}

	protected boolean preExecute(Request request, Response response) throws Exception {
		ChainItem next = head;
		while (next != null) {
			boolean result = next.filter.preExecute(request, response);
			if (result) {
				next = next.next;
			} else {
				next = null;
				return false;
			}
		}
		return true;
	}
}
